#include "panelsumary.h"
#include "pmclientdata.h"
#include "pm/manager.h"
#include "pm/summary.h"
#include "pm/project.h"
#include <boost/foreach.hpp>

PanelSumary::PanelSumary(wxWindow* parent)
: PanelSumaryGui(parent)
{
	wxTheApp->Connect(pmEVT_PROJECT_LOADED, wxCommandEventHandler(PanelSumary::OnProjectLoaded), NULL, this);
	
	pmConnect(pmEVT_COST_ADDED,         pm::Cost,        PanelSumary::OnCostChanged);
	pmConnect(pmEVT_COST_UPDATED,       pm::Cost,        PanelSumary::OnCostChanged);
	pmConnect(pmEVT_WORK_REQUEST_ADDED, pm::WorkRequest, PanelSumary::OnWorkRequestChanged);
	pmConnect(pmEVT_TASK_ADDED,         pm::Task,        PanelSumary::OnTaskChanged);
	pmConnect(pmEVT_TASK_UPDATED,       pm::Task,        PanelSumary::OnTaskChanged);
}

/**
 * 
 */
void PanelSumary::UpdatePanel(int project_id)
{
	if (project_id != wxGetApp().GetActiveProject()) {
		return;
	}
	
	pm::GetSummaryByProject critSummary(project_id);
	pm::select(critSummary);
	const pm::Summary& summary = critSummary.m_result;
	m_editWorkingRequest->SetValue(wxString::Format(wxT("%.2f"), summary.work_request()));
	m_editCost->SetValue(wxString::Format(wxT("%.2f"), summary.cost()));
	m_editTodo->SetValue(wxString::Format(wxT("%.2f"), summary.todo()));
	m_editEstimation->SetValue(wxString::Format(wxT("%.2f"), summary.estimation()));
	m_editBenefit->SetValue(wxString::Format(wxT("%.2f"), summary.benefit()));
	
	m_editBenefit->SetBackgroundColour(summary.benefit() > 0 ? *wxGREEN : *wxRED);
}

/**
 * \param event
 */
void PanelSumary::OnProjectLoaded(wxCommandEvent& event)
{
	event.Skip();
wxLogMessage(wxT("PanelSumary::OnProjectLoaded()"));
	UpdatePanel(event.GetInt());
}

/**
 * \param event
 */
void PanelSumary::OnWorkRequestChanged(pmEvent<pm::WorkRequest>& event)
{
	event.Skip();
	UpdatePanel(event.GetContent().id_project());
}

/**
 * \param event
 */
void PanelSumary::OnCostChanged(pmEvent<pm::Cost>& event)
{
	event.Skip();
	UpdatePanel(wxGetApp().GetActiveProject());
}

/**
 * \param event
 */
void PanelSumary::OnTaskChanged(pmEvent<pm::Task>& event)
{
	event.Skip();
	UpdatePanel(event.GetContent().id_project());
}
